package com.farm2.llm.client.handle.impl;

import com.farm2.llm.client.exceptions.CloseTalkException;
import com.farm2.llm.client.handle.inter.Farm2LlmMessageHandleInter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.farm2.base.event.enums.F2EActionT;
import org.farm2.base.event.enums.F2EObjectT;
import org.farm2.base.event.face.Farm2Events;
import org.farm2.tools.web.dto.QuotingKnowDto;
import org.farm2.tools.web.dto.SendMsgDto;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class SseEmitterHandle implements Farm2LlmMessageHandleInter {
    private SseEmitter emitter;
    private SendMsgDto sendMsg;

    public SseEmitterHandle(SseEmitter emitter, SendMsgDto msg) {
        this.emitter = emitter;
        this.sendMsg = msg;
    }

    private String formatMsg(String msg) {
        System.out.println(msg);
        if (msg != null) {
            msg = msg.replace(" ", "[KG|KG]");
            msg = msg.replace("\n", "[HH|HH]");
        }
        return msg;
    }


    @Override
    public void onMsg(String msg) {
        try {
            msg = formatMsg(msg);
            emitter.send(SseEmitter.event()
                    .name("message")
                    .data(msg));
            sendMsg.setSysMsg(sendMsg.getSysMsg() + msg);
        } catch (Exception e) {
            try {
                emitter.completeWithError(e); // 如果出错，完成并返回错误
            } catch (Exception e1) {
                log.warn(e1.getMessage());
            }
            throw new CloseTalkException(e);
        }
    }

    @Override
    public void onClosed() {
        System.out.println("----------关闭---------------");
        try {
            if (sendMsg.getQuotingKnows().size() > 0) {
                Set<String> ids = new HashSet<>();
                emitter.send(SseEmitter.event()
                        .name("message")
                        .data("\n<br/><h3>推荐知识：</h3>\n<br/> "));
                for (QuotingKnowDto know : sendMsg.getQuotingKnows()) {
                    if (!ids.contains(know.getKnowid())) {
                        ids.add(know.getKnowid());
                        emitter.send(SseEmitter.event()
                                .name("message")
                                .data("[" + know.getTitle() + "](/knowview/" + know.getKnowid() + ") \n<br/>"));
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            emitter.complete(); // 完成流
        }
    }

    @Override
    public void onError(Throwable throwable, String s) {
        try {
            Farm2Events.emitError(s);
            emitter.send(SseEmitter.event()
                    .name("message")
                    .data("\n接口错误,可以联系管理员获取日志"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            emitter.complete();
        }
    }
}
